package com.yun.controller;

import org.apache.commons.io.Charsets;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import java.io.*;
import java.util.Base64;


@Controller
public class FileUploadController {

    @Value("${baseurl}")
    private String baseurl;

    @RequestMapping(value = "uploadPng", method = RequestMethod.POST)
    @ResponseBody
    public String  upload(String base64Info) throws Exception {
       // System.out.println("baseUrl::::;;;"+baseurl);
        boolean generateImage = GenerateImage(base64Info,".png");
        return generateImage==true?"成功":"失败";
    }


    @RequestMapping(value = "uploadMp4", method = RequestMethod.POST)
    @ResponseBody
    public String  uploadMp4(String base64Info) throws Exception {
        String r3 = base64Info.substring(base64Info.indexOf(",")+1);
        String[] split = base64Info.split(",");
        GenerateImage(split[1],".mp4");
        return"成功";
    }



    //base64字符串转化成图片
    public  boolean GenerateImage(String imgStr,String type)

    {   //对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) //图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try
        {
            //Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for(int i=0;i<b.length;++i)
            {
                if(b[i]<0)
                {//调整异常数据
                    b[i]+=256;
                }
            }
            //生成jpeg图片
            String imgFilePath = baseurl+System.currentTimeMillis()+type;//新生成的图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }




    @ResponseBody
    @RequestMapping(value = "test", method = RequestMethod.GET)
    public String test1ss() throws Exception {
        return "123";
    }
}